using System;
using System.Collections;
using System.Collections.Generic;

namespace Tycho.Parser.Peg {
    public class ImmutableStackNode<T> : IEnumerable<T> {
        private readonly ImmutableStackNode<T> PreviousNode;
        public T Item { get; private set; }

        public ImmutableStackNode () {
            IsEmpty = true;
        }

        public ImmutableStackNode (ImmutableStackNode<T> previousNode, T item) {
            IsEmpty = false;
            PreviousNode = previousNode;
            Item = item;
        }

        public ImmutableStackNode<T> Push (T item) {
            return new ImmutableStackNode<T> (this, item);
        }

        public bool IsEmpty { get; private set; }

        public ImmutableStackNode<T> Pop () {
            if (IsEmpty) {
                throw new InvalidOperationException ("stack is empty");
            } else {
                return PreviousNode;
            }
        }

        public IEnumerator<T> GetEnumerator () {
            ImmutableStackNode<T> node = this;
            while (!node.IsEmpty) {
                yield return node.Item;
                node = node.PreviousNode;
            }
        }

        IEnumerator IEnumerable.GetEnumerator () {
            return GetEnumerator ();
        }
    }
}